<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能论文分类系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --gradient-primary: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --shadow-lg: 0 10px 20px rgba(0,0,0,0.1);
        }

        body {
            background: #f8f9fa;
            min-height: 100vh;
        }

        .main-card {
            border-radius: 1rem;
            border: none;
            box-shadow: var(--shadow-lg);
            background: white;
            transition: transform 0.3s;
        }

        .main-card:hover {
            transform: translateY(-5px);
        }

        .form-control:focus {
            box-shadow: 0 0 0 0.25rem rgba(118, 75, 162, 0.25);
        }

        .progress-bar {
            background: var(--gradient-primary);
        }

        #historyList {
            max-height: 400px;
            overflow-y: auto;
        }

        .history-item {
            transition: all 0.3s;
            cursor: pointer;
        }

        .history-item:hover {
            background: #f8f9fa;
            transform: translateX(10px);
        }
    </style>
</head>
<body class="py-5">
    <div class="container">
        <!-- 标题 -->
        <div class="text-center mb-5">
            <h1 class="display-4 fw-bold text-primary">
                <i class="fas fa-brain me-3"></i>智能论文分类系统
            </h1>
            <p class="text-muted">基于Transformer架构的学术论文智能分类与推荐</p>
        </div>

        <!-- 主功能卡片 -->
        <div class="row g-4">
            <!-- 分类模块 -->
            <div class="col-lg-8">
                <div class="main-card p-4 h-100">
                    <h4 class="mb-4">
                        <i class="fas fa-tag me-2"></i>论文分类
                    </h4>
                    <form id="classifyForm">
                        <div class="mb-4">
                            <label class="form-label fw-bold">论文标题</label>
                            <input type="text" class="form-control form-control-lg"
                                   id="title" placeholder="请输入论文标题" required>
                        </div>
                        <div class="mb-4">
                            <label class="form-label fw-bold">论文摘要</label>
                            <textarea class="form-control form-control-lg"
                                      id="abstract" rows="5"
                                      placeholder="请输入论文摘要" required>
                            </textarea>
                            <div class="mb-3">
                                <small class="text-muted">实时预览：</small>
                                <div id="abstractPreview" class="border p-2 rounded"></div>
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary btn-lg w-100">
                            <i class="fas fa-rocket me-2"></i>立即分析
                        </button>
                    </form>

                    <!-- 结果展示 -->
                    <div id="result" class="mt-4" style="display: none;">
                        <div class="card border-0 bg-light">
                            <div class="card-body">
                                <h5 class="card-title">
                                    <i class="fas fa-chart-bar me-2"></i>分析结果
                                </h5>
                                <div class="progress mb-3" style="height: 25px;">
                                    <div class="progress-bar progress-bar-striped"
                                         role="progressbar" style="width: 0%">
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="alert alert-primary">
                                            <strong>预测类别</strong>:
                                            <span id="categoryResult"></span>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="alert alert-success">
                                            <strong>置信度</strong>:
                                            <span id="probabilityResult"></span>%
                                        </div>
                                    </div>
                                </div>
                                <div class="mt-4">
                                    <canvas id="confidenceChart"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 侧边功能栏 -->
            <div class="col-lg-4">
                <!-- 历史记录 -->
                <div class="main-card p-4 mb-4">
                    <h5 class="mb-3">
                        <i class="fas fa-history me-2"></i>最近分析
                    </h5>
                    <div id="historyList" class="list-group">
                        <!-- 动态生成历史记录 -->
                    </div>
                </div>

                <!-- 快捷推荐 -->
                <div class="main-card p-4">
                    <h5 class="mb-3">
                        <i class="fas fa-lightbulb me-2"></i>热门领域
                    </h5>
                    <div class="d-flex flex-wrap gap-2" id="quickFields">
                        <button class="btn btn-outline-primary btn-sm"
                                onclick="loadQuickField('cs.CV')">计算机视觉</button>
                        <button class="btn btn-outline-primary btn-sm"
                                onclick="loadQuickField('cs.LG')">机器学习</button>
                        <button class="btn btn-outline-primary btn-sm"
                                onclick="loadQuickField('physics.optics')">光学物理</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 分类表单处理
        document.getElementById('classifyForm').onsubmit = async (e) => {
            e.preventDefault();
            const title = document.getElementById('title').value.trim();
            const abstract = document.getElementById('abstract').value.trim();

            if (!title || !abstract) {
                showAlert('请输入标题和摘要', 'danger');
                return;
            }

            showLoading();

            try {
                const response = await fetch('/classify', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ title, abstract })
                });

                if (!response.ok) throw new Error(`HTTP错误 ${response.status}`);

                const data = await response.json();
                showResult(data);
                addToHistory(title, data);
            } catch (error) {
                showAlert(`分类失败: ${error.message}`, 'danger');
            } finally {
                hideLoading();
            }
        };

        // 显示结果
        function showResult(data) {
            const resultDiv = document.getElementById('result');
            const progressBar = document.querySelector('.progress-bar');

            resultDiv.style.display = 'block';
            document.getElementById('categoryResult').textContent = data.category;
            document.getElementById('probabilityResult').textContent =
                (data.probability * 100).toFixed(1);

            progressBar.style.width = `${data.probability * 100}%`;
            progressBar.textContent = `${(data.probability * 100).toFixed(1)}%`;
        }

        // 可视化图表
        function renderChart(probability) {
            const ctx = document.getElementById('confidenceChart').getContext('2d');
            new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: ['置信度', '剩余'],
                    datasets: [{
                        data: [probability, 100 - probability],
                        backgroundColor: ['#4e73df', '#e74a3b']
                    }]
                }
            });
        }

        // 实时预览功能
        document.getElementById('abstract').addEventListener('input', function() {
            document.getElementById('abstractPreview').innerHTML =
                marked.parse(this.value);
        });

        // 历史记录功能
        let history = JSON.parse(localStorage.getItem('classificationHistory')) || [];

        function addToHistory(title, data) {
            const entry = {
                title: title.substring(0, 50) + (title.length > 50 ? '...' : ''),
                category: data.category,
                probability: data.probability,
                timestamp: new Date().toLocaleString()
            };

            history = [entry, ...history].slice(0, 5); // 保留最近5条
            localStorage.setItem('classificationHistory', JSON.stringify(history));
            renderHistory();
        }

        function renderHistory() {
            console.log("renderHistory()已被调用");
            alert("renderHistory()已被调用");
            const list = document.getElementById('historyList');
            list.innerHTML = history.map((item, index) => `
                <div class="list-group-item history-item">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="mb-1">${item.title}</h6>
                            <small class="text-muted">${item.timestamp}</small>
                        </div>
                        <span class="badge bg-primary">${item.category}</span>
                    </div>
                </div>
            `).join('');
        }

        // 初始化加载历史记录
        renderHistory();

        // 快捷领域加载
        function loadQuickField(field) {
            document.getElementById('fieldInput').value = field;
            loadKnowledgeGraph();
        }

        // 工具函数
        function showLoading() {
            document.getElementById('result').style.display = 'none';
            document.querySelector('button[type="submit"]').innerHTML = `
                <i class="fas fa-spinner fa-spin me-2"></i>分析中...
            `;
        }

        function hideLoading() {
            document.querySelector('button[type="submit"]').innerHTML = `
                <i class="fas fa-rocket me-2"></i>立即分析
            `;
        }

        function showAlert(message, type = 'success') {
            const alert = document.createElement('div');
            alert.className = `alert alert-${type} alert-dismissible fade show`;
            alert.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;

            document.body.prepend(alert);
            setTimeout(() => alert.remove(), 3000);
        }
    </script>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</body>
</html>